package com.ruoyi.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.product.contanst.CacheKey;
import com.ruoyi.product.domain.CartItemVO;
import com.ruoyi.product.domain.CartVO;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.enums.BizCodeEnum;
import com.ruoyi.product.excepion.BizException;
import com.ruoyi.product.request.CartItemRequest;
import com.ruoyi.product.service.CartService;
import com.ruoyi.product.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private IProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void addToCart(CartItemRequest cartItemRequest) {
        String productId = String.valueOf(cartItemRequest.getProductId());
        int buyNum = cartItemRequest.getBuyNum();

        //获取购物车
        BoundHashOperations<String,Object,Object> myCart =  getMyCartOps();

        String cacheObj = (String) myCart.get(productId);
        String result = "";

        if(cacheObj!=null){
            result =  cacheObj;
        }

        if(StringUtils.isBlank(result)){
            //不存在则新建一个商品
            CartItemVO cartItemVO = new CartItemVO();

            Product product = productService.selectProductById(String.valueOf(productId));
            if(product == null){throw new BizException(BizCodeEnum.CART_FAIL);}

            cartItemVO.setAmount(product.getAmount());
            cartItemVO.setBuyNum(buyNum);
            cartItemVO.setProductId(Long.valueOf(productId));
            cartItemVO.setProductImg(product.getCoverImg());
            cartItemVO.setProductTitle(product.getTitle());
            cartItemVO.setWeight(product.getWeight());
            myCart.put(productId, JSON.toJSONString(cartItemVO));
        }else {
            //存在商品，修改数量
            CartItemVO cartItem = JSON.parseObject(result,CartItemVO.class);
            cartItem.setBuyNum(cartItem.getBuyNum()+buyNum);
            myCart.put(productId,JSON.toJSONString(cartItem));
        }

    }

    @Override
    public List<CartItemVO> confirmOrderCartItems(List<String> productIdList) {

        //获取全部购物车的购物项
        List<CartItemVO> cartItemVOList =  buildCartItem(true);

        //根据需要的商品id进行过滤，并清空对应的购物项
        List<CartItemVO> resultList =  cartItemVOList.stream().filter(obj->{

            if(productIdList.contains(obj.getProductId().toString())){
                System.out.println(obj.getProductId());
                this.deleteItem(String.valueOf(obj.getProductId()));
                return true;
            }
            return false;

        }).collect(Collectors.toList());
        System.out.println("resultList: "+resultList);
        return resultList;
    }


    /**
     * 删除购物项
     * @param productId
     */
    @Override
    public void deleteItem(String productId) {

        BoundHashOperations<String,Object,Object> mycart =  getMyCartOps();
        mycart.delete(productId);

    }

    @Override
    public CartVO getMyCart() {
        //获取全部购物项
        List<CartItemVO> cartItemVOList = buildCartItem(false);
        List<Long> productList = cartItemVOList.stream().map(CartItemVO::getProductId).collect(Collectors.toList());
        //封装成cartvo
        CartVO cartVO = new CartVO();
        cartVO.setCartItems(cartItemVOList);
        cartVO.setProductIds(productList);
        return cartVO;
    }

    /**
     * 抽取我的购物车，通用方法
     * @return
     */
    private BoundHashOperations<String,Object,Object> getMyCartOps(){
        String cartKey = getCartKey();
        return redisTemplate.boundHashOps(cartKey);
    }


    /**
     * 购物车 key
     * @return
     */
    private String getCartKey(){

        String cartKey = String.format(CacheKey.CART_KEY,1l);
        return cartKey;
    }

    /**
     * 获取最新的购物项，
     * @param latestPrice 是否获取最新价格
     * @return
     */
    private List<CartItemVO> buildCartItem(boolean latestPrice) {

        BoundHashOperations<String,Object,Object> myCart = getMyCartOps();

        List<Object> itemList = myCart.values();

        List<CartItemVO> cartItemVOList = new ArrayList<>();

        //拼接id列表查询最新价格
        List<Long> productIdList = new ArrayList<>();

        for(Object item: itemList){
            CartItemVO cartItemVO = JSON.parseObject((String)item,CartItemVO.class);
            cartItemVOList.add(cartItemVO);

            productIdList.add(cartItemVO.getProductId());
        }

        //查询最新的商品价格
        if(latestPrice){
            setProductLatestPrice(cartItemVOList,productIdList);
        }

        return cartItemVOList;

    }

    /**
     * 设置商品最新价格
     * @param cartItemVOList
     * @param productIdList
     */
    private void setProductLatestPrice(List<CartItemVO> cartItemVOList, List<Long> productIdList) {

        //批量查询
        List<Product> productList = productService.findProductsByIdBatch(productIdList);

        //分组
        Map<String,Product> maps = productList.stream().collect(Collectors.toMap(Product::getId, Function.identity()));


        cartItemVOList.stream().forEach(item->{
            System.out.println(item.getProductTitle());
            Product product = maps.get(item.getProductId().toString());
            item.setProductTitle(product.getTitle());
            item.setProductImg(product.getCoverImg());
            item.setAmount(product.getAmount());
        });
    }
}
